package cn.blunce.weather.activities;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import cn.blunce.weather.R;
import cn.blunce.weather.base.AppDB;
import cn.blunce.weather.models.CityID;
import cn.blunce.weather.models.DailyForcast;
import cn.blunce.weather.models.WeatherAQI;
import cn.blunce.weather.models.WeatherSuggestion;
import cn.blunce.weather.utils.GetWeatherData;
import cn.blunce.weather.utils.ParseUtils;
import cn.blunce.weather.utils.Urls;
import cn.blunce.weather.utils.Utils;
import cn.blunce.weather.utils.WeatherInfo;
import cn.blunce.weather.view.PullRefreshView;
import cn.blunce.weather.view.SlideMenu;

public class WeatherShowActivity extends Activity implements View.OnClickListener,
        AdapterView.OnItemLongClickListener,
        AdapterView.OnItemClickListener {

    private CityID mCurCity;

    private AppDB mAppDB;

    private WeatherInfo mWeatherInfo;

    private PullRefreshView mPullRefreshView;

    private int[][] mViewId_DailyForcast = {
            {R.id.tv_time_dailyforcast_1, R.id.iv_photo_dailyforcast_1, R.id.tv_tmp_dailyforcast_1},
            {R.id.tv_time_dailyforcast_2, R.id.iv_photo_dailyforcast_2, R.id.tv_tmp_dailyforcast_2},
            {R.id.tv_time_dailyforcast_3, R.id.iv_photo_dailyforcast_3, R.id.tv_tmp_dailyforcast_3}
    };


    private ListView mLV_cities;

    private ArrayAdapter<String> mAdapter;
    private List<CityID> mCities;

    private EditText mET_search_city;
    private ListView mLV_search_suggestion;

    private List<CityID> mDialogCities;
    private ArrayAdapter<String> mDialogAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather_show);

        initPara();
        initView();

        mPullRefreshView.update();
        weather_update();
        Log.i("test", "hello");
    }

    private void initPara() {
        mAppDB = AppDB.getInstance(WeatherShowActivity.this);
        mCurCity = Utils.readCities(WeatherShowActivity.this, mAppDB).get(0);

        mCities = Utils.readCities(this, mAppDB);
        mAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, Utils.getCityNames(mCities));
    }

    private void initView() {
        findViewById(R.id.btn_add_city).setOnClickListener(this);
        mLV_cities = (ListView) findViewById(R.id.list_cities);
        mLV_cities.setAdapter(mAdapter);

        mLV_cities.setOnItemClickListener(this);
        mLV_cities.setOnItemLongClickListener(this);

        mPullRefreshView = (PullRefreshView) findViewById(R.id.prv_pull_refresh);
        mPullRefreshView.setOnRefreshListener(new PullRefreshView.PullToRefreshListener() {
            @Override
            public void onRefresh() {
                weather_update();
            }
        }, 0);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_add_city:
                addCity();
                break;

            case R.id.iv_suggestion_comf:
            case R.id.tv_suggestion_title_comf:
            case R.id.tv_suggestion_info_comf:
                ((ImageView) findViewById(R.id.iv_suggestion_detail)).setImageResource(R.drawable.suggestion_comf);
                ((TextView) findViewById(R.id.tv_suggestion_detail_title)).setText(
                        getResources().getText(R.string.suggestion_comf) + ":" +
                                mWeatherInfo.getmWeatherMessage().getSuggestion().getComf().getBrf()
                );
                ((TextView) findViewById(R.id.tv_suggestion_detail_info)).setText(
                        mWeatherInfo.getmWeatherMessage().getSuggestion().getComf().getTxt()
                );
                findViewById(R.id.ll_suggestion_all).setVisibility(View.GONE);
                findViewById(R.id.ll_suggestion_detail).setVisibility(View.VISIBLE);
                break;

            case R.id.iv_suggestion_drsg:
            case R.id.tv_suggestion_title_drsg:
            case R.id.tv_suggestion_info_drsg:
                ((ImageView) findViewById(R.id.iv_suggestion_detail)).setImageResource(R.drawable.suggestion_drsg);
                ((TextView) findViewById(R.id.tv_suggestion_detail_title)).setText(
                        getResources().getText(R.string.suggestion_drsg) + ":" +
                                mWeatherInfo.getmWeatherMessage().getSuggestion().getDrsg().getBrf()
                );
                ((TextView) findViewById(R.id.tv_suggestion_detail_info)).setText(
                        mWeatherInfo.getmWeatherMessage().getSuggestion().getDrsg().getTxt()
                );
                ((LinearLayout) findViewById(R.id.ll_suggestion_all)).setVisibility(View.GONE);
                ((LinearLayout) findViewById(R.id.ll_suggestion_detail)).setVisibility(View.VISIBLE);
                break;

            case R.id.iv_suggestion_flu:
            case R.id.tv_suggestion_title_flu:
            case R.id.tv_suggestion_info_flu:
                ((ImageView) findViewById(R.id.iv_suggestion_detail)).setImageResource(R.drawable.suggestion_flu);
                ((TextView) findViewById(R.id.tv_suggestion_detail_title)).setText(
                        getResources().getText(R.string.suggestion_flu) + ":" +
                                mWeatherInfo.getmWeatherMessage().getSuggestion().getFlu().getBrf()
                );
                ((TextView) findViewById(R.id.tv_suggestion_detail_info)).setText(
                        mWeatherInfo.getmWeatherMessage().getSuggestion().getFlu().getTxt()
                );
                ((LinearLayout) findViewById(R.id.ll_suggestion_all)).setVisibility(View.GONE);
                ((LinearLayout) findViewById(R.id.ll_suggestion_detail)).setVisibility(View.VISIBLE);
                break;

            case R.id.iv_suggestion_sport:
            case R.id.tv_suggestion_title_sport:
            case R.id.tv_suggestion_info_sport:
                ((ImageView) findViewById(R.id.iv_suggestion_detail)).setImageResource(R.drawable.suggestion_sport);
                ((TextView) findViewById(R.id.tv_suggestion_detail_title)).setText(
                        getResources().getText(R.string.suggestion_sport) + ":" +
                                mWeatherInfo.getmWeatherMessage().getSuggestion().getSport().getBrf()
                );
                ((TextView) findViewById(R.id.tv_suggestion_detail_info)).setText(
                        mWeatherInfo.getmWeatherMessage().getSuggestion().getSport().getTxt()
                );
                ((LinearLayout) findViewById(R.id.ll_suggestion_all)).setVisibility(View.GONE);
                ((LinearLayout) findViewById(R.id.ll_suggestion_detail)).setVisibility(View.VISIBLE);
                break;

            case R.id.iv_suggestion_trav:
            case R.id.tv_suggestion_title_traw:
            case R.id.tv_suggestion_info_traw:
                ((ImageView) findViewById(R.id.iv_suggestion_detail)).setImageResource(R.drawable.suggestion_trav);
                ((TextView) findViewById(R.id.tv_suggestion_detail_title)).setText(
                        getResources().getText(R.string.suggestion_trav) + ":" +
                                mWeatherInfo.getmWeatherMessage().getSuggestion().getTraw().getBrf()
                );
                ((TextView) findViewById(R.id.tv_suggestion_detail_info)).setText(
                        mWeatherInfo.getmWeatherMessage().getSuggestion().getTraw().getTxt()
                );
                ((LinearLayout) findViewById(R.id.ll_suggestion_all)).setVisibility(View.GONE);
                ((LinearLayout) findViewById(R.id.ll_suggestion_detail)).setVisibility(View.VISIBLE);
                break;

            case R.id.iv_suggestion_uv:
            case R.id.tv_suggestion_title_uv:
            case R.id.tv_suggestion_info_uv:
                ((ImageView) findViewById(R.id.iv_suggestion_detail)).setImageResource(R.drawable.suggestion_uv);
                ((TextView) findViewById(R.id.tv_suggestion_detail_title)).setText(
                        getResources().getText(R.string.suggestion_uv) + ":" +
                                mWeatherInfo.getmWeatherMessage().getSuggestion().getUv().getBrf()
                );
                ((TextView) findViewById(R.id.tv_suggestion_detail_info)).setText(
                        mWeatherInfo.getmWeatherMessage().getSuggestion().getUv().getTxt()
                );
                ((LinearLayout) findViewById(R.id.ll_suggestion_all)).setVisibility(View.GONE);
                ((LinearLayout) findViewById(R.id.ll_suggestion_detail)).setVisibility(View.VISIBLE);
                break;

            case R.id.ll_suggestion_detail:
            case R.id.iv_suggestion_detail:
            case R.id.tv_suggestion_detail_title:
            case R.id.tv_suggestion_detail_info:
                ((LinearLayout) findViewById(R.id.ll_suggestion_all)).setVisibility(View.VISIBLE);
                ((LinearLayout) findViewById(R.id.ll_suggestion_detail)).setVisibility(View.GONE);
                break;
            default:

        }
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        mCurCity = mCities.get(position);
        ((SlideMenu) findViewById(R.id.sm_slide_menu)).toggle();
        ((TextView) findViewById(R.id.tv_city_name)).setText(mCurCity.getCity());

        mPullRefreshView.update();
        weather_update();
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
        new AlertDialog.Builder(this).setTitle("删除").setMessage("是否删除该城市？").setPositiveButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mCities.remove(position);
                mAdapter.remove(mAdapter.getItem(position));
                mLV_cities.setAdapter(mAdapter);
            }
        }).setNegativeButton("否", null).show();
        return false;
    }

    private void weather_update() {

        new AsyncTask<CityID, Void, WeatherInfo>() {
            @Override
            protected void onPreExecute() {
                mWeatherInfo = new WeatherInfo();
            }

            @Override
            protected WeatherInfo doInBackground(CityID... params) {
                String url_city_id = Urls.getUrl(Urls.URL_INDEX_SEARCH_WEATHER,
                        params[0].getId());
                String message = GetWeatherData.request(url_city_id);
                try {
                    mWeatherInfo.setmWeatherMessage(
                            ParseUtils.ParseAndAddWeatherMessage(message, mAppDB)
                    );
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }

                try {
                    String weatherPhotoCode = mWeatherInfo.getmWeatherMessage()
                            .getNow().getCond_now().getCode();
                    Bitmap bitmap = Utils.readPhotoCache(WeatherShowActivity.this, weatherPhotoCode);
                    if (bitmap == null) {
                        bitmap = GetWeatherData.getWeatherPhoto(
                                Urls.getUrl(
                                        Urls.URL_INDEX_DOWNLOAD_WEATHER_PHOTO,
                                        weatherPhotoCode
                                )
                        );
                        mWeatherInfo.setmWeatherPhoto(bitmap);
                        Utils.savePhotoCache(WeatherShowActivity.this, weatherPhotoCode, bitmap);
                    } else
                        mWeatherInfo.setmWeatherPhoto(bitmap);

                    List<DailyForcast> dailyForcasts =
                            mWeatherInfo.getmWeatherMessage().getDaily_forcasts();
                    List<Bitmap> photos = new ArrayList<>();
                    for (int i = 0; i < 3 && i < dailyForcasts.size(); i++) {
                        weatherPhotoCode = dailyForcasts.get(i).getCond().getCode_d();
                        bitmap = Utils.readPhotoCache(WeatherShowActivity.this, weatherPhotoCode);
                        if (bitmap == null) {
                            bitmap = GetWeatherData.getWeatherPhoto(
                                    Urls.getUrl(
                                            Urls.URL_INDEX_DOWNLOAD_WEATHER_PHOTO,
                                            weatherPhotoCode
                                    )
                            );
                            Utils.savePhotoCache(WeatherShowActivity.this, weatherPhotoCode, bitmap);
                            photos.add(bitmap);
                        } else
                            photos.add(bitmap);
                    }
                    mWeatherInfo.setmDailyForcastPhotos(photos);

                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
                return mWeatherInfo;
            }

            @Override
            protected void onPostExecute(WeatherInfo weatherInfo) {
                if (weatherInfo != null) {
                    ((TextView) findViewById(R.id.tv_city_name)).setText(mCurCity.getCity());
                    ((TextView) findViewById(R.id.tv_weather_text)).setText(
                            weatherInfo.getmWeatherMessage().getNow().getCond_now().getTxt());
                    ((TextView) findViewById(R.id.tv_weather_tmp)).setText(
                            weatherInfo.getmWeatherMessage().getNow().getTmp() + "℃");
                    ((ImageView) findViewById(R.id.iv_weather_photo)).setImageBitmap(
                            weatherInfo.getmWeatherPhoto());

                    List<DailyForcast> dailyForcasts = weatherInfo.
                            getmWeatherMessage().getDaily_forcasts();
                    for (int i = 0; i < dailyForcasts.size() && i < 3; i++) {
                        ((TextView) findViewById(mViewId_DailyForcast[i][0])).setText(
                                dailyForcasts.get(i).getDate());
                        ((ImageView) findViewById(mViewId_DailyForcast[i][1])).setImageBitmap(
                                weatherInfo.getmDailyForcastPhotos().get(i));
                        ((TextView) findViewById(mViewId_DailyForcast[i][2])).setText(
                                dailyForcasts.get(i).getTmp().getMax() + "℃/"
                                        + dailyForcasts.get(i).getTmp().getMin() + "℃");
                    }

                    WeatherSuggestion weatherSuggestion = weatherInfo.getmWeatherMessage().getSuggestion();
                    ((TextView) findViewById(R.id.tv_suggestion_info_comf)).setText(weatherSuggestion.getComf().getBrf());
                    ((TextView) findViewById(R.id.tv_suggestion_info_drsg)).setText(weatherSuggestion.getDrsg().getBrf());
                    ((TextView) findViewById(R.id.tv_suggestion_info_flu)).setText(weatherSuggestion.getFlu().getBrf());
                    ((TextView) findViewById(R.id.tv_suggestion_info_sport)).setText(weatherSuggestion.getSport().getBrf());
                    ((TextView) findViewById(R.id.tv_suggestion_info_traw)).setText(weatherSuggestion.getTraw().getBrf());
                    ((TextView) findViewById(R.id.tv_suggestion_info_uv)).setText(weatherSuggestion.getUv().getBrf());

                    WeatherAQI weatherAQI = weatherInfo.getmWeatherMessage().getAqi();
                    ((TextView) findViewById(R.id.tv_aqi_qlty)).setText(
                            "空气质量：" + weatherAQI.getQlty()
                    );
                    ((TextView) findViewById(R.id.tv_aqi_pm25)).setText(
                            "PM2.5: " + weatherAQI.getPm25() + getResources().getString(R.string.unit_pm25)
                    );
                }

                mPullRefreshView.finishRefreshing();
            }
        }.execute(mCurCity);
    }


    private void addCity() {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_add_city, null);
        mET_search_city = (EditText) dialogView.findViewById(R.id.et_search_city);
        mLV_search_suggestion = (ListView) dialogView.findViewById(R.id.lv_search_suggestion);

        mET_search_city.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mDialogCities = mAppDB.queryCitiesByNames(String.valueOf(s));
                mDialogAdapter = new ArrayAdapter<>(WeatherShowActivity.this, android.R.layout.simple_list_item_1, Utils.getCityNames(mDialogCities));
                mLV_search_suggestion.setAdapter(mDialogAdapter);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mLV_search_suggestion.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mET_search_city.setText(mDialogAdapter.getItem(position));
            }
        });

        new AlertDialog.Builder(this).setTitle("添加城市").setView(dialogView).setPositiveButton("添加", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mCities.add(mDialogCities.get(0));
                mAdapter.add(mDialogCities.get(0).getCity());
                mLV_cities.setAdapter(mAdapter);
            }
        }).setNegativeButton("取消", null).show();
    }
}
